import { plainToInstance } from "class-transformer";
import QuestionDao from "../dao/QuestionDao";
import QuestionEntity from "../entities/QuestionEntity";
import ResultHelper from "../utils/ResultHelper";

export default class QuenstionService {

  static async create(question: Object) {
    const Q = plainToInstance(QuestionEntity, question)

    const errs = await Q.validateThie()

    if (errs.length > 0) {
      return ResultHelper.error(errs)
    }

    const result = await QuestionDao.create(Q)

    return ResultHelper.success({}, "添加成功")

  }

  static async delete(id: string) {
    const result = await QuestionDao.delete(id)

    if (result) {
      // 删除 成功
      return ResultHelper.success({}, "删除成功")
    } else {
      return ResultHelper.error("删除失败")
    }
  }

  static async findByPage(page: number = 1, limit: number = 10) {

    const offset = ((+page) - 1) * (+limit)

    const result = await QuestionDao.findByPage(offset, limit)

    return ResultHelper.success(result)
  }

  static async findById(id: string) {
    if (!id) {
      return ResultHelper.error('没有试唯一标识')
    }

    const result = await QuestionDao.findById(id)
    return ResultHelper.success(result)
  }
}